#include <stdio.h>
#include <pthread.h>

int counter = 0;      // 全局变量
pthread_mutex_t lock; // 互斥锁

void *increment_counter(void *arg)
{
    for (int i = 0; i < 100000; i++)
    {
        pthread_mutex_lock(&lock); // 加锁
        counter++;
        pthread_mutex_unlock(&lock); // 解锁
    }

    return NULL;
}

int main()
{
    pthread_mutex_init(&lock, NULL); // 初始化互斥锁
    pthread_t t1, t2;

    pthread_create(&t1, NULL, increment_counter, NULL);
    pthread_create(&t2, NULL, increment_counter, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    pthread_mutex_destroy(&lock); // 销毁互斥锁
    printf("最终的counter的值：%d\n", counter);
    return 0;
}